﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;

namespace Think9.Services.Com
{
    public class PageCom
    {
        private static string split = Think9.Services.Base.BaseConfig.ComSplit;//字符分割 用于多选项的分割等
        private static string _dbtype = Think9.Services.Base.Configs.GetDBProvider("DBProvider");//数据库类型

        public PageCom()
        {
        }

        //为隐藏指标赋初始值
        public static string EditHideIndexDefaultValue(string flowid, long listid, CurrentUserEntity user)
        {
            string err = "";
            if (listid > 0)
            {
                string tbid = flowid.Replace("bi_", "tb_").Replace("fw_", "tb_");
                string indexId;
                string dataType;
                string ruleType;
                string ruleId;
                string defaultV;
                string strV;
                string updateFields = "";
                string link;
                ComService comService = new ComService();

                DataTable dt = comService.GetDataTable("tbindex", "RuleType,IndexId,RuleId,DataType,DefaultV", "TbId='" + tbid + "' and isShow='2' ", "");
                foreach (DataRow drIndex in dt.Rows)
                {
                    indexId = drIndex["IndexId"].ToString();
                    dataType = drIndex["DataType"].ToString();
                    ruleType = drIndex["RuleType"].ToString();
                    ruleId = drIndex["RuleId"].ToString();
                    defaultV = drIndex["DefaultV"].ToString().Trim();//默认值

                    if (ruleType == "1" || defaultV != "")
                    {
                        if (dataType.StartsWith("1"))//日期
                        {
                            strV = TbIndex.GetDefaultValue(user, dt, indexId);

                            if (strV != "" && ValidatorHelper.IsDateTime(strV))
                            {
                                link = string.IsNullOrEmpty(updateFields) ? "" : ", ";
                                updateFields += link + indexId + "='" + strV + "'";
                            }
                        }

                        if (dataType.StartsWith("2"))//字符型
                        {
                            strV = TbIndex.GetDefaultValue(user, dt, indexId);
                            if (strV != "")
                            {
                                link = string.IsNullOrEmpty(updateFields) ? "" : ", ";
                                updateFields += link + indexId + "='" + strV + "'";
                            }
                        }

                        if (dataType.StartsWith("3"))//数字
                        {
                            if (defaultV != "" && ValidatorHelper.IsNumberic(defaultV))
                            {
                                link = string.IsNullOrEmpty(updateFields) ? "" : ", ";
                                updateFields += link + indexId + "=" + defaultV + "";
                            }
                        }

                        if (dataType.StartsWith("5"))//图片
                        {
                            if (defaultV != "")
                            {
                                link = string.IsNullOrEmpty(updateFields) ? "" : ", ";
                                updateFields += link + indexId + "='" + defaultV + "'";
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(updateFields))
                {
                    string sql = "update " + tbid + " set " + updateFields + "  where listid = " + listid + " ";
                    int count = comService.ExecuteSql(sql, null, "隐藏指标赋初始值");
                    Record.Add("system", listid.ToString(), flowid, "#隐藏指标赋初始值##影响行数{" + count + "}##" + sql.Trim() + "#");
                    err = count > 0 ? "" : "隐藏指标赋初始值失败";
                }
            }
            return err;
        }

        public static string EditHideIndexDefaultValue(string flowid, string gidid, long listid, long id, CurrentUserEntity user)
        {
            string err = "";
            if (id > 0)
            {
                string indexId;
                string dataType;
                string ruleType;
                string ruleId;
                string defaultV;
                string strV;
                string updateFields = "";
                string link;
                ComService comService = new ComService();

                DataTable dt = comService.GetDataTable("tbindex", "RuleType,IndexId,RuleId,DataType,DefaultV", "TbId='" + gidid + "' and isShow='2'", "");
                foreach (DataRow drIndex in dt.Rows)
                {
                    indexId = drIndex["IndexId"].ToString();
                    dataType = drIndex["DataType"].ToString();
                    ruleType = drIndex["RuleType"].ToString();
                    ruleId = drIndex["RuleId"].ToString();
                    defaultV = drIndex["DefaultV"].ToString().Trim();//默认值

                    if (ruleType == "1" || defaultV != "")
                    {
                        if (dataType.StartsWith("1"))//日期
                        {
                            strV = TbIndex.GetDefaultValue(user, dt, indexId);

                            if (strV != "" && ValidatorHelper.IsDateTime(strV))
                            {
                                link = string.IsNullOrEmpty(updateFields) ? "" : ", ";
                                updateFields += link + indexId + "='" + strV + "'";
                            }
                        }

                        if (dataType.StartsWith("2"))//字符型
                        {
                            strV = TbIndex.GetDefaultValue(user, dt, indexId);
                            if (strV != "")
                            {
                                link = string.IsNullOrEmpty(updateFields) ? "" : ", ";
                                updateFields += link + indexId + "='" + strV + "'";
                            }
                        }

                        if (dataType.StartsWith("3"))//数字
                        {
                            if (defaultV != "" && ValidatorHelper.IsNumberic(defaultV))
                            {
                                link = string.IsNullOrEmpty(updateFields) ? "" : ", ";
                                updateFields += link + indexId + "=" + defaultV + "";
                            }
                        }

                        if (dataType.StartsWith("5"))//图片
                        {
                            if (defaultV != "")
                            {
                                link = string.IsNullOrEmpty(updateFields) ? "" : ", ";
                                updateFields += link + indexId + "='" + defaultV + "'";
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(updateFields))
                {
                    string sql = "update " + gidid + " set " + updateFields + "  where id = " + id + " ";
                    int count = comService.ExecuteSql(sql, null, "隐藏指标赋初始值");
                    Record.Add("system", listid.ToString(), flowid, "#隐藏指标赋初始值##影响行数{" + count + "}##" + sql.Trim() + "#");
                    err = count > 0 ? "" : "隐藏指标赋初始值失败";
                }
            }
            return err;
        }

        public static long GeListIdByHttpRequest(string maintbid, Microsoft.AspNetCore.Http.HttpRequest request)
        {
            long listid = -100;
            string where = "";
            string dataType = "";
            string indexId = "";
            ComService comService = new ComService();

            DataTable dtFieldList = comService.GetTbFieldsList(maintbid);
            foreach (DataRow row in dtFieldList.Rows)
            {
                indexId = row["COLUMN_NAME"].ToString();
                dataType = row["DATA_type"].ToString();
                if (!string.IsNullOrEmpty(request.Query[indexId]))
                {
                    // todo 还需补全
                    if (dataType.Contains("int") || dataType.Contains("decimal") || dataType.Contains("long") || dataType.Contains("numeric") || dataType.Contains("real") || dataType.Contains("float"))
                    {
                        if (where == "")
                        {
                            where += indexId + " = " + request.Query[indexId].ToString() + "";
                        }
                        else
                        {
                            where += " AND " + indexId + " = " + request.Query[indexId].ToString() + "";
                        }
                    }
                    else
                    {
                        if (where == "")
                        {
                            where += indexId + " = '" + request.Query[indexId].ToString() + "'";
                        }
                        else
                        {
                            where += " AND " + indexId + " = '" + request.Query[indexId].ToString() + "'";
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(where))
            {
                DataTable dt = comService.GetDataTable(maintbid, "listid", where, "");
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows.Count == 1)
                    {
                        listid = long.Parse(dt.Rows[0]["listid"].ToString());
                    }
                }
                else
                {
                    listid = 0;
                }
            }

            return listid;
        }

        public static DataTable GetMainTbDt(ref string err, string fwid, string listid, string hostUrl, string pathUserImg, string pathImgNoExist)
        {
            string temp = "";

            ComService comService = new ComService();
            string maintbid = fwid.Replace("bi_", "tb_").Replace("fw_", "tb_");
            DataTable dtExternalDb = comService.GetDataTable("select * from externaldb");

            DataTable dtReturn = new DataTable(maintbid);

            try
            {
                DataTable dtindex = comService.GetDataTable("tbindex", "*", "TbId='" + maintbid + "'", "");

                dtReturn.Columns.Add("listid", typeof(String));
                foreach (DataRow row in dtindex.Rows)
                {
                    dtReturn.Columns.Add(row["IndexId"].ToString(), typeof(String));
                    //图片
                    if (row["DataType"].ToString().StartsWith("5"))
                    {
                        dtReturn.Columns.Add(row["IndexId"].ToString() + "_Exa", typeof(String));
                    }
                }

                DataTable dtMain = comService.GetDataTable(maintbid, "*", "where listid=" + listid + "", "");
                if (dtMain.Rows.Count > 0)
                {
                    DataTable dtValueText = DataTableHelp.NewValueTextDt();

                    List<ModelRule> listRule = GetRuleModelListByTbID(maintbid, dtindex, _dbtype);//model.SqlList
                    foreach (ModelRule obj in listRule)
                    {
                        if (obj.ControlType == "2" || obj.ControlType == "3" || obj.ControlType == "4")
                        {
                            if (!string.IsNullOrEmpty(obj.SqlList))
                            {
                                DataTable dt = new DataTable();
                                if (obj.DbID == "0")
                                {
                                    dt = comService.GetDataTable(obj.SqlList);
                                }
                                else
                                {
                                    string dbType = "";
                                    string dbCon = "";
                                    string sql = obj.SqlList;
                                    foreach (DataRow dr in dtExternalDb.Rows)
                                    {
                                        if (dr["DbID"].ToString() == obj.DbID)
                                        {
                                            dbType = dr["DbType"].ToString();
                                            dbCon = dr["DbCon"].ToString();
                                            if (dbType == "postgresql")
                                            {
                                                sql = obj.SqlList_PG;
                                            }
                                            if (dbType == "oracle")
                                            {
                                                sql = obj.SqlList_ORACLE;
                                            }
                                            break;
                                        }
                                    }
                                    dt = comService.GetDataTable(dbCon, dbType, sql);
                                }
                                foreach (DataRow dr in dt.Rows)
                                {
                                    DataRow row = dtValueText.NewRow();
                                    row["ClassID"] = obj.IndexId;
                                    row["Value"] = dr["id"].ToString();
                                    row["Text"] = dr["name"].ToString();
                                    dtValueText.Rows.Add(row);
                                }
                            }
                        }
                    }

                    DataRow rowDB = dtReturn.NewRow();
                    foreach (DataRow row in dtindex.Rows)
                    {
                        string sIndexId = row["IndexId"].ToString();
                        string sIndexName = row["IndexName"].ToString();
                        string sDataType = row["DataType"].ToString();
                        string sNO = row["IndexNo"].ToString();//序号
                                                               //1：text文本框 2：select下拉选择 3：checkbox复选框 4：radio单选框 5：img图片
                        string sControlType = row["ControlType"].ToString();
                        sControlType = sControlType == "" ? "1" : sControlType;

                        if (sDataType.StartsWith("1"))//日期
                        {
                            temp = dtMain.Rows[0][sIndexId].ToString().Trim();
                            if (row["isTime"].ToString() == "1")
                            {
                                rowDB[sIndexId] = temp;
                            }
                            else
                            {
                                rowDB[sIndexId] = temp;
                                if (temp != "")
                                {
                                    rowDB[sIndexId] = DateTime.Parse(temp).ToString("yyyy-MM-dd");
                                }
                            }
                        }

                        if (sDataType.StartsWith("2"))//字符型
                        {
                            temp = dtMain.Rows[0][sIndexId].ToString();
                            rowDB[sIndexId] = temp;

                            //select下拉选择
                            if (sControlType == "2")
                            {
                                string strV = "";
                                foreach (DataRow drVT in dtValueText.Rows)
                                {
                                    if (drVT["Value"].ToString() == temp && drVT["ClassID"].ToString() == sIndexId)
                                    {
                                        strV = drVT["Text"].ToString();
                                        break;
                                    }
                                }
                                rowDB[sIndexId] = strV;
                            }

                            //checkbox复选框
                            if (sControlType == "3")
                            {
                                string strV = "";
                                foreach (DataRow drVT in dtValueText.Rows)
                                {
                                    if (drVT["ClassID"].ToString() == sIndexId)
                                    {
                                        if (temp.Contains(split + drVT["Value"].ToString() + split))
                                        {
                                            strV += "【√】" + drVT["Text"].ToString() + " ";
                                        }
                                        else
                                        {
                                            strV += "〔 〕" + drVT["Text"].ToString() + " ";
                                        }
                                    }
                                }

                                rowDB[sIndexId] = strV;
                            }

                            //radio单选框〔 〕◯（●）（○）
                            if (sControlType == "4")
                            {
                                string strV = "";
                                foreach (DataRow drVT in dtValueText.Rows)
                                {
                                    if (drVT["ClassID"].ToString() == sIndexId)
                                    {
                                        if (drVT["Value"].ToString() == temp)
                                        {
                                            strV += "【√】" + drVT["Text"].ToString() + " ";
                                        }
                                        else
                                        {
                                            strV += "〔 〕" + drVT["Text"].ToString() + " ";
                                        }
                                    }
                                }
                                rowDB[sIndexId] = strV;
                            }
                        }

                        if (sDataType.StartsWith("3"))//数字
                        {
                            temp = dtMain.Rows[0][sIndexId].ToString().Trim();
                            rowDB[sIndexId] = temp;
                            //金额写法
                            if (sDataType == "3102" && temp != "")
                            {
                                rowDB[sIndexId] = "¥" + temp;
                            }
                        }

                        if (sDataType.StartsWith("5"))//图片
                        {
                            temp = "file:///" + pathImgNoExist;
                            if (dtMain.Rows[0][sIndexId].ToString().Trim() != "")
                            {
                                if (System.IO.File.Exists(pathUserImg + dtMain.Rows[0][sIndexId].ToString().Trim()))
                                {
                                    temp = "file:///" + pathUserImg + dtMain.Rows[0][sIndexId].ToString().Trim();
                                    if (!string.IsNullOrEmpty(hostUrl))
                                    {
                                        //显示原图
                                        rowDB[sIndexId + "_Exa"] = hostUrl + "/UserImg/_" + dtMain.Rows[0][sIndexId].ToString().Trim();
                                    }
                                }
                            }
                            rowDB[sIndexId] = temp;
                        }
                    }

                    dtReturn.Rows.Add(rowDB);
                }
                else
                {
                    err = "数据不存在";
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
            }

            return dtReturn;
        }

        public static DataTable GetGridTbDt(ref string err, string fwid, string listid, string hostUrl, string pathUserImg, string pathImgNoExist)
        {
            DataTable dtReturn = DataTableHelp.NewGridDt();
            int num = 0;
            string temp = "";
            string grtbId = "";
            DataTable dtindex;
            ComService comService = new ComService();
            DataTable dtExternalDb = comService.GetDataTable("select * from externaldb");

            string maintbid = fwid.Replace("bi_", "tb_").Replace("fw_", "tb_");

            foreach (DataRow drtb in comService.GetDataTable("tbbasic", "TbId", "ParentId='" + maintbid + "'", "").Rows)
            {
                grtbId = drtb["TbId"].ToString();

                dtindex = comService.GetDataTable("tbindex", "*", "TbId='" + grtbId + "'", "");
                List<ModelRule> listRule = GetRuleModelListByTbID(grtbId, dtindex, _dbtype);

                DataTable dtValueText = DataTableHelp.NewValueTextDt();

                foreach (ModelRule obj in listRule)
                {
                    if (obj.ControlType == "2")
                    {
                        if (!string.IsNullOrEmpty(obj.SqlList))
                        {
                            DataTable dt = new DataTable();
                            if (obj.DbID == "0")
                            {
                                dt = comService.GetDataTable(obj.SqlList);
                            }
                            else
                            {
                                string dbType = "";
                                string dbCon = "";
                                string sql = obj.SqlList;
                                foreach (DataRow dr in dtExternalDb.Rows)
                                {
                                    if (dr["DbID"].ToString() == obj.DbID)
                                    {
                                        dbType = dr["DbType"].ToString();
                                        dbCon = dr["DbCon"].ToString();
                                        if (dbType == "postgresql")
                                        {
                                            sql = obj.SqlList_PG;
                                        }
                                        if (dbType == "oracle")
                                        {
                                            sql = obj.SqlList_ORACLE;
                                        }
                                        break;
                                    }
                                }
                                dt = comService.GetDataTable(dbCon, dbType, sql);
                            }
                            foreach (DataRow dr in dt.Rows)
                            {
                                DataRow row = dtValueText.NewRow();
                                row["ClassID"] = obj.IndexId;
                                row["Value"] = dr["id"].ToString();
                                row["Text"] = dr["name"].ToString();
                                dtValueText.Rows.Add(row);
                            }
                        }
                    }
                }

                num = 0;
                DataTable dtGrid = comService.GetDataTable(grtbId, "*", "where listid=" + listid + "", "");
                foreach (DataRow dr30 in dtGrid.Rows)
                {
                    num++;

                    DataRow rowDB = dtReturn.NewRow();
                    rowDB["listid"] = listid;
                    rowDB["tbid"] = grtbId;
                    rowDB["num"] = num;

                    foreach (DataRow rowindex in dtindex.Rows)
                    {
                        string _indexId = rowindex["IndexId"].ToString();
                        string _dataType = rowindex["DataType"].ToString();
                        //1：text文本框 2：select下拉选择 3：checkbox复选框 4：radio单选框 5：img图片
                        string _controlType = rowindex["ControlType"].ToString();
                        _controlType = _controlType == "" ? "1" : _controlType;

                        if (_dataType.StartsWith("1"))//日期
                        {
                            temp = dr30[_indexId].ToString().Trim();
                            if (rowindex["isTime"].ToString() == "1")
                            {
                                rowDB[_indexId] = temp;
                            }
                            else
                            {
                                rowDB[_indexId] = temp;
                                if (temp != "")
                                {
                                    rowDB[_indexId] = DateTime.Parse(temp).ToString("yyyy-MM-dd");
                                }
                            }
                        }

                        if (_dataType.StartsWith("2"))//字符型
                        {
                            temp = dr30[_indexId].ToString();
                            rowDB[_indexId] = temp;

                            //select下拉选择
                            if (_controlType == "2")
                            {
                                string strV = "";
                                foreach (DataRow drVT in dtValueText.Rows)
                                {
                                    if (drVT["Value"].ToString() == temp && drVT["ClassID"].ToString() == _indexId)
                                    {
                                        strV = drVT["Text"].ToString();
                                        break;
                                    }
                                }
                                rowDB[_indexId] = strV;
                            }
                        }

                        if (_dataType.StartsWith("3"))//数字
                        {
                            temp = dr30[_indexId].ToString().Trim();
                            rowDB[_indexId] = temp;
                            //金额写法
                            if (_dataType == "3102" && temp != "")
                            {
                                rowDB[_indexId] = "¥" + temp;
                            }
                        }

                        if (_dataType.StartsWith("5"))//图片
                        {
                            temp = "file:///" + pathImgNoExist;
                            if (dr30[_indexId].ToString().Trim() != "")
                            {
                                if (System.IO.File.Exists(pathUserImg + dr30[_indexId].ToString().Trim()))
                                {
                                    temp = "file:///" + pathUserImg + dr30[_indexId].ToString().Trim();
                                    if (!string.IsNullOrEmpty(hostUrl))
                                    {
                                        //显示原图
                                        rowDB[_indexId + "_Exa"] = hostUrl + "/UserImg/_" + dr30[_indexId].ToString().Trim();
                                    }
                                }
                            }
                            rowDB[_indexId] = temp;
                        }
                    }

                    dtReturn.Rows.Add(rowDB);
                }

                //合计行
                var _index = DataTableHelp.ToEnumerable<TbIndexEntity>(dtindex);
                if (_index.Where(x => x.ControlType == "1" && x.ListStat == "1" && x.DataType.StartsWith("3")).Count<TbIndexEntity>() > 0)//条件 1数值指标2文本框3统计求和
                {
                    DataRow rowDB = dtReturn.NewRow();
                    rowDB["listid"] = listid;
                    rowDB["tbid"] = grtbId;

                    foreach (TbIndexEntity item in _index)
                    {
                        if (item.ControlType == "1" && item.ListStat == "1" && item.DataType.StartsWith("3"))
                        {
                            rowDB[item.IndexId] = "∑ = " + comService.GetSingleField("select SUM(" + item.IndexId + ") from " + grtbId + " where ListId = " + listid + "");
                        }
                    }

                    dtReturn.Rows.Add(rowDB);
                }
            }

            return dtReturn;
        }

        /// <summary>
        /// 返回待接手where
        /// </summary>
        /// <param name="user">当前用户信息</param>
        /// <param name="key"></param>
        /// <param name="fwid"></param>
        /// <returns></returns>
        public static string GetManageWhere(CurrentUserEntity user, string fwid, string key)
        {
            ComService ComService = new ComService();

            string where = "where FlowId='" + fwid + "' ";
            string Account = user.Account == null ? ";!NullEx;" : ";" + user.Account + ";";
            string DeptNo = user.DeptNo == null ? ";!NullEx;" : "." + user.DeptNo + ".";
            string RoleNo = user.RoleNo == null ? ";!NullEx;" : ";" + user.RoleNo + ";";

            string isall = "2";//是否可以管理所有数据？1可以2不可以--只能管理本部门及下级部门
            string ManageUser = ComService.GetSingleField("select ManageUser from Flow where FlowId = '" + fwid + "'");
            if (ManageUser.Contains(Account) || ManageUser.Trim() == "#all#")
            {
                isall = "1";
            }
            if (isall != "1")
            {
                where += "  and (createDeptStr like'%" + DeptNo + "%')";
            }

            if (!string.IsNullOrEmpty(key))
            {
                where += "  and (runName like'%" + key + "%' or ruNumber like'%" + key + "%'   ) ";
            }

            return where;
        }

        /// <summary>
        /// 返回待接手where
        /// </summary>
        /// <param name="user">当前用户信息</param>
        /// <param name="key"></param>
        /// <param name="fwid"></param>
        /// <returns></returns>
        public static string GetManageWhere2(CurrentUserEntity user, string fwid, string key)
        {
            ComService ComService = new ComService();

            string where = "where 1=1 ";
            string Account = user.Account == null ? ";!NullEx;" : ";" + user.Account + ";";
            string DeptNo = user.DeptNo == null ? ";!NullEx;" : "." + user.DeptNo + ".";
            string RoleNo = user.RoleNo == null ? ";!NullEx;" : ";" + user.RoleNo + ";";

            string isAll = "2";//是否可以管理所有数据？1可以2不可以--只能管理本部门及下级部门
            string ManageUser = ComService.GetSingleField("select ManageUser from Flow where FlowId = '" + fwid + "'");
            if (ManageUser.Contains(Account) || ManageUser.Trim() == "#all#")
            {
                isAll = "1";
            }

            if (isAll != "1")
            {
                where += "  and (createDeptStr like'%" + DeptNo + "%')";
            }

            if (!string.IsNullOrEmpty(key))
            {
                where += "  and (runName like'%" + key + "%') ";
            }

            return where;
        }

        /// <summary>
        ///添加一条空数据
        /// </summary>
        /// <param name="maintbid">录入表主表编码或者多表的主表编码</param>
        /// <param name="flowid">0独立模式不与flowrunlist关联</param>
        /// <returns></returns>
        public static long InsertEmptyReturnID(ref string err, string flowid, string flowname, CurrentUserEntity user, CurrentPrcsEntity mCurrentPrcs)
        {
            long listid = 0;
            err = "";
            string maintbid = flowid.Replace("bi_", "tb_").Replace("fw_", "tb_");
            ComService comService = new ComService();

            if (user != null)
            {
                string userid = user.Account;
                string deptno = user.DeptNo;
                string depnostr = user.DeptNoStr;
                //基础信息表 listid自增长
                if (flowid.StartsWith("bi_"))
                {
                    List<string> columns = new List<string>();
                    columns.Add("isLock");
                    columns.Add("createTime");
                    columns.Add("createUser");
                    columns.Add("createDept");
                    columns.Add("createDeptStr");
                    columns.Add("runName");
                    columns.Add("state");

                    object param = new { isLock = 0, state = 1, createTime = DateTime.Now.ToString(), createUser = userid, createDept = deptno, createDeptStr = depnostr, runName = BaseUtil.GetRunName(userid, flowid, flowname) };

                    listid = comService.InsertAndReturnID(maintbid, columns, param);

                    Record.Add("system", listid.ToString(), flowid, "#新增空数据##自动编号或新增子表数据引发#");
                }
                else
                {
                    listid = FlowRunList.InsertFlowrunListReturnID(ref err, maintbid, flowid, flowname, mCurrentPrcs, user);
                    if (listid > 0)
                    {
                        List<string> columns = new List<string>();

                        columns.Add("listid");
                        columns.Add("state");

                        object param = new { listid = listid, state = 1 };

                        comService.Insert(maintbid, columns, param);

                        Record.Add("system", listid.ToString(), flowid, "#新增空数据##自动编号或新增子表数据引发#");
                    }
                }
            }

            return listid;
        }

        public static TbBasicEntity GetDetailButon(string listid, string fwid)
        {
            ComService ComService = new ComService();
            TbBasicEntity model = new TbBasicEntity();

            string txt = "";
            string warn = "";
            string id = "";
            DataTable dt = ComService.GetDataTable("select * from tbbut where TbID='" + fwid.Replace("bi_", "tb_").Replace("fw_", "tb_") + "'");

            txt = "附件";
            warn = "";
            id = "0";
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["BtnId"].ToString() == "attdetails")
                {
                    txt = dr["BtnText"].ToString();
                    warn = dr["BtnWarn"].ToString();
                    id = "1";
                    break;
                }
            }
            model.ButAtt = id;
            model.ButAttWarn = warn;
            if (id == "1")
            {
                string attId = "";
                if (fwid.StartsWith("bi_"))
                {
                    attId = ComService.GetSingleField("select attachmentId  FROM " + fwid.Replace("bi_", "tb_") + " WHERE listid= " + listid);
                }
                else
                {
                    attId = ComService.GetSingleField("select attachmentId  FROM flowrunlist WHERE listid= " + listid);
                }

                if (string.IsNullOrEmpty(attId))
                {
                    model.ButAttTxt = txt + "(0)";
                }
                else
                {
                    model.ButAttTxt = txt + "(" + ComService.GetSingleField("select count(*) FROM flowattachment WHERE attachmentId='" + attId + "' ") + ")";
                }
            }

            txt = "打开PDF";
            id = "0";
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["BtnId"].ToString() == "pdfdetails")
                {
                    txt = dr["BtnText"].ToString();
                    id = "1";
                    break;
                }
            }
            model.ButPDFDetails = id;
            model.ButPDFDetailsTxt = txt;

            txt = "导出EXCEL";
            id = "0";
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["BtnId"].ToString() == "exceldetails")
                {
                    txt = dr["BtnText"].ToString();
                    id = "1";
                    break;
                }
            }
            model.ButExcelDetails = id;
            model.ButExcelDetailsTxt = txt;

            txt = "导出DOC";
            id = "0";
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["BtnId"].ToString() == "docdetails")
                {
                    txt = dr["BtnText"].ToString();
                    id = "1";
                    break;
                }
            }
            model.ButDOCDetails = id;
            model.ButDOCDetailsTxt = txt;

            return model;
        }

        private static List<ModelRule> GetRuleModelListByTbID(string tbid, DataTable dtindex, string _dbtype)
        {
            ComService comService = new ComService();

            DataTable dtrulesingle = comService.GetDataTable("RuleSingle", "*", "", "");
            DataTable dtrulemultiple = comService.GetDataTable("rulemultiple", "*", "", "");
            DataTable dtrulemultiplefiled = comService.GetDataTable("rulemultiplefiled", "*", "", "");
            DataTable dtruletree = comService.GetDataTable("ruletree", "*", "", "");

            List<ModelRule> mList = new List<ModelRule>();

            string _where = "";

            string _order = "";
            string _order2 = "";

            string _select = "";
            string _select2 = "";

            string _from = "";
            string _from_PG = "";
            string _from_ORACLE = "";

            string sql_list = "";
            string sql_list_PG = "";
            string sql_list_ORACLE = "";

            string sql_form = "";
            string sql_form_PG = "";
            string sql_form_ORACLE = "";

            string sControlType = "";
            foreach (DataRow row in dtindex.Rows)
            {
                if (row["RuleId"].ToString() != "")
                {
                    List<IdValueModel> list = new List<IdValueModel>();
                    ModelRule model = new ModelRule();

                    //1：text文本框 2：select下拉选择 3：checkbox复选框 4：radio单选框 5：img图片
                    sControlType = "1";
                    if (row["ControlType"].ToString().Trim() != "")
                    {
                        sControlType = row["ControlType"].ToString();
                    }
                    sControlType = sControlType == "" ? "1" : sControlType;

                    model.TbId = row["TbId"].ToString();
                    model.IndexId = row["IndexId"].ToString();
                    model.IndexName = row["IndexName"].ToString();
                    model.isSelMuch = row["isSelMuch"].ToString();//是否可多选？1可以2不可以

                    model.ControlType = sControlType;
                    model.DataType = row["DataType"].ToString();
                    model.RuleId = row["RuleId"].ToString();
                    model.RuleType = row["RuleType"].ToString();
                    model.DataType = row["DataType"].ToString();

                    //6单列
                    if (model.RuleType == "6")
                    {
                        foreach (DataRow drule in dtrulesingle.Rows)
                        {
                            if (drule["RuleId"].ToString() == model.RuleId)
                            {
                                model.DbID = drule["DbID"].ToString();
                                model.SearchFiled = drule["RuleBy"].ToString();
                                model.ValueFiled = drule["ValueFiled"].ToString();//值字段
                                model.TxtFiled = drule["TxtFiled"].ToString();//显示字段
                                model.OrderFiled = drule["OrderFiled"].ToString();//排序字段
                                model.ValueScope = drule["ValueScope"].ToString();//1固定取值2动态取值
                                model.FrmTB = drule["TbId"].ToString();//取值数据表
                                model.LimitStr = drule["LimitStr"].ToString().Replace("\\\"", "\"");//筛选条件
                                model.OrderType = drule["OrderType"].ToString();
                                model.DictItemId = drule["DictItemId"].ToString();

                                list.Add(new IdValueModel { ID = "Value", Value = drule["ValueFiled"].ToString(), Text = "" });
                                list.Add(new IdValueModel { ID = "info1", Value = drule["ValueFiled"].ToString(), Text = "编码" });
                                list.Add(new IdValueModel { ID = "info2", Value = drule["TxtFiled"].ToString(), Text = "名称" });
                            }
                        }
                    }

                    //6多列
                    if (model.RuleType == "7")
                    {
                        foreach (DataRow drule in dtrulemultiple.Rows)
                        {
                            if (drule["RuleId"].ToString() == model.RuleId)
                            {
                                model.DbID = drule["DbID"].ToString();
                                model.SearchFiled = drule["RuleBy"].ToString();
                                model.ValueFiled = drule["ValueFiled"].ToString();//值字段
                                model.TxtFiled = drule["TxtFiled"].ToString();//显示字段
                                model.OrderFiled = drule["OrderFiled"].ToString();//排序字段
                                model.ValueScope = drule["ValueScope"].ToString();//1固定取值2动态取值
                                model.FrmTB = drule["TbId"].ToString();//取值数据表
                                model.LimitStr = drule["LimitStr"].ToString().Replace("\\\"", "\"");//筛选条件
                                model.OrderType = drule["OrderType"].ToString();
                                model.DictItemId = drule["DictItemId"].ToString();

                                list.Add(new IdValueModel { ID = "Value", Value = drule["ValueFiled"].ToString(), Text = "" });

                                break;
                            }
                        }

                        int icount = 0;
                        foreach (DataRow drule in dtrulemultiplefiled.Rows)
                        {
                            //注意最多10列
                            if (drule["RuleId"].ToString() == model.RuleId && int.Parse(drule["FiledOrder"].ToString()) > 0 && icount <= 10)
                            {
                                icount++;
                                string _filedValue = drule["FiledValue"].ToString();
                                string _name = TableHelp.GetIndexName(dtindex, model.FrmTB, _filedValue);
                                list.Add(new IdValueModel { ID = "info" + icount.ToString(), Value = _filedValue, Text = _name });
                            }
                        }
                    }

                    //树型
                    if (model.RuleType == "8")
                    {
                        foreach (DataRow drule in dtruletree.Rows)
                        {
                            if (drule["RuleId"].ToString() == model.RuleId)
                            {
                                model.DbID = drule["DbID"].ToString();
                                model.SearchFiled = drule["RuleBy"].ToString();
                                model.ValueFiled = drule["ValueFiled"].ToString();//值字段
                                model.TxtFiled = drule["TxtFiled"].ToString();//显示字段
                                model.OrderFiled = drule["OrderFiled"].ToString();//排序字段
                                model.ValueScope = drule["ValueScope"].ToString();//1固定取值2动态取值
                                model.FrmTB = drule["TbId"].ToString();//取值数据表
                                model.LimitStr = drule["LimitStr"].ToString().Replace("\\\"", "\"");//筛选条件
                                model.OrderType = drule["OrderType"].ToString();
                                model.DictItemId = drule["DictItemId"].ToString();

                                list.Add(new IdValueModel { ID = "Value", Value = drule["ValueFiled"].ToString(), Text = "" });
                                list.Add(new IdValueModel { ID = "info1", Value = drule["ValueFiled"].ToString(), Text = "编码" });
                                list.Add(new IdValueModel { ID = "info2", Value = drule["TxtFiled"].ToString(), Text = "名称" });

                                break;
                            }
                        }
                    }

                    //树选
                    if (model.RuleType == "8")
                    {
                        _select = model.ValueFiled + " as id," + model.TxtFiled + " as name";
                        _select2 = "\"" + model.ValueFiled + "\"" + " as id," + "\"" + model.TxtFiled + "\"" + " as name";
                        if (model.ValueScope == "1")
                        {
                            _where = "ItemCode='" + model.DictItemId + "'";

                            _from = "sys_itemsdetail";
                            _from_PG = "\"sys_itemsdetail\"";
                            _from_ORACLE = "\"sys_itemsdetail\"";

                            _order = "LENGTH(DetailCode), OrderNo";
                            _order2 = "LENGTH(DetailCode), OrderNo";
                            if (_dbtype != "mysql")
                            {
                                _order = "LEN(DetailCode), OrderNo";
                                _order2 = "LEN(DetailCode), OrderNo";
                            }
                            if (model.OrderType == "2")
                            {
                                _order += " desc";
                                _order2 += " desc";
                            }

                            sql_list = "select " + _select + " FROM " + _from + " where " + _where + " ORDER BY " + _order;
                            sql_list_PG = "select " + _select2 + " FROM " + _from_PG + " where " + _where + " ORDER BY " + _order2;
                            sql_list_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + _where + " ORDER BY " + _order2;

                            sql_form = "select " + _select + " FROM " + _from + " where " + _where + " ORDER BY " + _order;
                            sql_form_PG = "select " + _select2 + " FROM " + _from_PG + " where " + _where + " ORDER BY " + _order2;
                            sql_form_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + _where + " ORDER BY " + _order2;
                        }
                        else
                        {
                            _from = model.FrmTB;
                            _from_PG = "\"" + model.FrmTB + "\"";
                            _from_ORACLE = "\"" + model.FrmTB + "\"";

                            _where = " ";

                            _order = "LENGTH(" + model.ValueFiled + ") ";
                            _order2 = "LENGTH(" + model.ValueFiled + ") ";
                            if (_dbtype != "mysql")
                            {
                                _order = "LEN(" + model.ValueFiled + ") ";
                                _order2 = "LEN(" + model.ValueFiled + ") ";
                            }

                            if (model.OrderFiled.Trim() != "")
                            {
                                _order += " ," + model.OrderFiled.Trim();
                                _order2 += " ," + model.OrderFiled.Trim();
                                if (model.OrderType == "2")
                                {
                                    _order += " desc";
                                    _order2 += " desc";
                                }
                            }

                            sql_list = "select " + _select + " FROM " + _from + " ORDER BY " + _order;
                            sql_list_PG = "select " + _select2 + " FROM " + _from_PG + " ORDER BY " + _order2;
                            sql_list_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " ORDER BY " + _order2;

                            sql_form = "select " + _select + " FROM " + _from + " ORDER BY " + _order;
                            sql_form_PG = "select " + _select2 + " FROM " + _from_PG + " ORDER BY " + _order2;
                            sql_form_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " ORDER BY " + _order2;
                        }
                    }
                    else
                    {
                        _select = model.ValueFiled + " as id," + model.TxtFiled + " as name";
                        _select2 = "\"" + model.ValueFiled + "\"" + " as id," + "\"" + model.TxtFiled + "\"" + " as name";
                        if (model.ValueScope == "1")
                        {
                            _from = "sys_itemsdetail";
                            _from_PG = "\"sys_itemsdetail\"";
                            _from_ORACLE = "\"sys_itemsdetail\"";

                            _where = "ItemCode = '" + model.DictItemId + "'";
                            _order = "OrderNo";
                            if (model.OrderType == "2")
                            {
                                _order += " desc";
                            }

                            if (!string.IsNullOrEmpty(model.LimitStr))
                            {
                                sql_form = "select " + _select + " FROM " + _from + " where " + _where + " AND " + model.LimitStr + " order by " + _order;
                                sql_form_PG = "select " + _select2 + " FROM " + _from_PG + " where " + _where + " AND " + model.LimitStr + " order by " + _order2;
                                sql_form_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + _where + " AND " + model.LimitStr + " order by " + _order2;
                                //包含系统参数
                                if (model.LimitStr.Trim().Contains("@"))
                                {
                                    sql_list = "select " + _select + " FROM " + _from + " where " + _where + " order by " + _order;
                                    sql_list_PG = "select " + _select2 + " FROM " + _from_PG + " where " + _where + " order by " + _order2;
                                    sql_list_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + _where + " order by " + _order2;
                                }
                                else
                                {
                                    sql_list = "select " + _select + " FROM " + _from + " where " + _where + " AND " + model.LimitStr + " order by " + _order;
                                    sql_list_PG = "select " + _select2 + " FROM " + _from_PG + " where " + _where + " AND " + model.LimitStr + " order by " + _order2;
                                    sql_list_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + _where + " AND " + model.LimitStr + " order by " + _order2;
                                }
                            }
                            else
                            {
                                sql_list = "select " + _select + " FROM " + _from + " where " + _where + " order by " + _order;
                                sql_list_PG = "select " + _select2 + " FROM " + _from_PG + " where " + _where + " order by " + _order2;
                                sql_list_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + _where + " order by " + _order2;

                                sql_form = "select " + _select + " FROM " + _from + " where " + _where + " order by " + _order;
                                sql_form_PG = "select " + _select2 + " FROM " + _from_PG + " where " + _where + " order by " + _order2;
                                sql_form_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + _where + " order by " + _order2;
                            }
                        }
                        else
                        {
                            _where = "";

                            _from = model.FrmTB;
                            _from_PG = "\"" + model.FrmTB + "\"";
                            _from_ORACLE = "\"" + model.FrmTB + "\"";

                            _order = model.OrderFiled;
                            _order2 = "\"" + model.OrderFiled + "\"";
                            if (model.OrderType == "2" && _order.Trim() != "")
                            {
                                _order += " desc";
                                _order2 += " desc";
                            }

                            if (!string.IsNullOrEmpty(model.LimitStr))
                            {
                                sql_form = "select " + _select + " FROM " + _from + " where " + model.LimitStr + " order by " + _order;
                                sql_form_PG = "select " + _select2 + " FROM " + _from_PG + " where " + model.LimitStr + " order by " + _order2;
                                sql_form_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + model.LimitStr + " order by " + _order2;

                                //包含系统参数
                                if (model.LimitStr.Trim().Contains("@"))
                                {
                                    sql_list = "select " + _select + " FROM " + _from + " order by " + _order;
                                    sql_list_PG = "select " + _select2 + " FROM " + _from_PG + " order by " + _order2;
                                    sql_list_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " order by " + _order2;
                                }
                                else
                                {
                                    sql_list = "select " + _select + " FROM " + _from + " where " + model.LimitStr + " order by " + _order;
                                    sql_list_PG = "select " + _select2 + " FROM " + _from_PG + " where " + model.LimitStr + " order by " + _order2;
                                    sql_list_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " where " + model.LimitStr + " order by " + _order2;
                                }
                            }
                            else
                            {
                                sql_list = "select " + _select + " FROM " + _from + " order by " + _order;
                                sql_list_PG = "select " + _select2 + " FROM " + _from_PG + " order by " + _order2;
                                sql_list_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " order by " + _order2;

                                sql_form = "select " + _select + " FROM " + _from + " order by " + _order;
                                sql_form_PG = "select " + _select2 + " FROM " + _from_PG + " order by " + _order2;
                                sql_form_ORACLE = "select " + _select2 + " FROM " + _from_ORACLE + " order by " + _order2;
                            }
                        }
                    }

                    model.SqlForm = sql_form;
                    model.SqlForm_PG = sql_form_PG;
                    model.SqlForm_ORACLE = sql_form_ORACLE;

                    model.SqlList = sql_list;
                    model.SqlList_PG = sql_list_PG;
                    model.SqlList_ORACLE = sql_list_ORACLE;

                    model.list = list;
                    mList.Add(model);
                }
            }

            return mList;
        }
    }
}

//private static string GetValueByRule(string ruleId, CurrentUserEntity user)
//{
//	string str = "";
//	if (ruleId.ToLower() == "sysusername")
//	{
//		str = user.RealName;
//	}
//	if (ruleId.ToLower() == "sysuserid")
//	{
//		str = user.Account;
//	}
//	if (ruleId.ToLower() == "sysdeptno")
//	{
//		str = user.DeptNo;
//	}
//	if (ruleId.ToLower() == "sysdeptname")
//	{
//		str = user.DeptName;
//	}
//	if (ruleId.ToLower() == "sysroleno")
//	{
//		str = user.RoleNo;
//	}
//	if (ruleId.ToLower() == "sysrolename")
//	{
//		str = user.RoleName;
//	}
//	if (ruleId.ToLower() == "sysday")
//	{
//		str = DateTime.Today.ToString("yyyy-MM-dd");
//	}
//	if (ruleId.ToLower() == "systime")
//	{
//		str = DateTime.Now.ToString();
//	}
//	if (ruleId.ToLower() == "systimenow")
//	{
//		str = DateTime.Now.ToString();
//	}

//	return str;
//}

//private static string GetValueByDefaultV(string defaultV, CurrentUserEntity user)
//{
//	string str = "";
//	if (defaultV.ToLower() == "@sysusername")
//	{
//		str = user.RealName;
//	}
//	if (defaultV.ToLower() == "@sysuserid")
//	{
//		str = user.Account;
//	}
//	if (defaultV.ToLower() == "@sysdeptno")
//	{
//		str = user.DeptNo;
//	}
//	if (defaultV.ToLower() == "@sysdeptname")
//	{
//		str = user.DeptName;
//	}
//	if (defaultV.ToLower() == "@sysroleno")
//	{
//		str = user.RoleNo;
//	}
//	if (defaultV.ToLower() == "@sysrolename")
//	{
//		str = user.RoleName;
//	}
//	if (defaultV.ToLower() == "@sysday")
//	{
//		str = DateTime.Today.ToString("yyyy-MM-dd");
//	}
//	if (defaultV.ToLower() == "@systime")
//	{
//		str = DateTime.Now.ToString();
//	}
//	if (defaultV.ToLower() == "@systimenow")
//	{
//		str = DateTime.Now.ToString();
//	}

//	if (str == "")
//	{
//		str = defaultV;
//	}

//	return str;
//}